package com.cloud.common.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加解密工具类
 */
public class CryptUtils {

    /**
     * 加密
     * @param data 需要加密的数据
     * @param secret 加密用的私钥
     * @return String
     */
    public static String encrypt(String data, String secret) throws Exception {
        if (data == null || secret == null || secret.length() != 16) {
            return null;
        }
        String charsetName = "utf-8";
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); //算法/模式/补码方式
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secret.getBytes(charsetName), "AES"));
        byte[] encrypted = cipher.doFinal(data.getBytes(charsetName));
        return Base64.encodeBase64URLSafeString(encrypted);//base64加密
    }

    /**
     * 解密
     * @param data
     * @param secret
     * @return String
     * @throws Exception
     */
    public static String decrypt(String data, String secret) throws Exception {
        if (data == null || secret == null || secret.length() != 16) {
            return null;
        }
        String charsetName = "utf-8";
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); //算法/模式/补码方式
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secret.getBytes(charsetName), "AES"));
        byte[] encrypted = Base64.decodeBase64(data);//base64解密
        return new String(cipher.doFinal(encrypted), charsetName);
    }

}
